"""
主服务模块
"""
import datetime
import time
import random
from typing import List, Tuple
from config.settings import SYSTEM_CONFIG
from config.candidates import CANDIDATES, DEFAULT_CANDIDATE
from utils.logger import logger
from utils.audio import audio_player
from utils.mail import mail_sender
from utils.date_utils import date_utils
from utils.network import network_client
from services.appointment_service import appointment_service


class MainService:
    """主服务类"""
    
    def __init__(self, user_id: str = None):
        self.config = SYSTEM_CONFIG
        self.user_id = user_id or 'default'
        # 根据配置设置网络debug模式
        debug_config = self.config.get('debug', {})
        network_debug = debug_config.get('network_requests', False)  # 默认关闭
        
        # 为每个用户创建独立的预约服务实例
        from services.appointment_service import AppointmentService
        self.appointment_service = AppointmentService(user_id=user_id)
        
        logger.log(f"主服务初始化完成 (用户: {self.user_id})，网络debug: {'开启' if network_debug else '关闭'}", "system")
    
    def run_candidate(self, candidate_name: str = None, custom_date_range: List[str] = None) -> bool:
        """运行单个候选人的预约流程"""
        if candidate_name is None:
            candidate_name = DEFAULT_CANDIDATE
        
        if candidate_name not in CANDIDATES:
            logger.log(f'候选人 {candidate_name} 不存在', 'system')
            return False
        
        candidate = CANDIDATES[candidate_name]
        candidate_info = candidate['info']
        service_name = candidate['service']
        first_name = candidate_info[1]  # 名字
        last_name = candidate_info[2]   # 姓氏
        name = first_name  # 保持向后兼容
        
        mailed = False
        retry_count = 0
        
        logger.log_user(f'开始处理候选人: {first_name} {last_name} - {service_name}', first_name, last_name)
        
        
        while retry_count < self.config['max_retries']:
            try:
                
                
                # 检查工作时间
                if not self._is_working_hours():
                    logger.log_user(f'{first_name}:当前为休息时间，暂停服务', first_name, last_name)
                    time.sleep(60)  # 休息时间等待1分钟
                    continue
                
                # 添加随机延迟
                delay = random.randint(*self.config['random_delay_range'])
                time.sleep(delay)
                
                logger.log_user(f'开始扫描可用时间段', first_name, last_name)
                
                # 获取可用日期 - 默认查找当月，无数据时往后延1个月，或使用用户指定范围
                if custom_date_range:
                    safe_dates = custom_date_range
                    logger.log_user(f'使用用户指定日期范围: {safe_dates}', first_name, last_name)
                else:
                    safe_dates = self._get_scan_dates()
                
                # 扫描可用时间段
                calendar_items, available_slots = self.appointment_service.scan_available_slots(
                    name, service_name, safe_dates
                )
                
                logger.log_user(f'扫描完成，找到 {len(available_slots)} 个可用时间段', first_name, last_name)
                
                
                if available_slots:
                    # 查找最佳时间
                    best_start, best_end = date_utils.find_best_time(available_slots)
                    
                    if best_start and best_end:
                        # 播放通知音
                        audio_player.play_notification()
                        
                        # 发送邮件通知
                        if not mailed:
                            mailed = mail_sender.send_notification(
                                f'{name}-{service_name}:最佳结果：时间段：[{best_start}-{best_end}]'
                            )
                        
                        logger.log_user(f'找到最佳时间段: {best_start} - {best_end}', first_name, last_name)
                        
                        # 检查时间是否符合用户指定的范围（如果有的话）
                        if custom_date_range and not self._is_time_in_range(best_start, custom_date_range):
                            logger.log_user(f'{first_name}:找到的时间段 {best_start} 不在用户指定范围内，跳过预约', first_name, last_name)
                            continue
                        
                        
                        # 尝试预约
                        calendar_item = calendar_items[f"{best_start}@{best_end}"]
                        success = self.appointment_service.book_appointment(
                            candidate_info, best_start, best_end, service_name, calendar_item
                        )
                        
                        if success:
                            logger.log_user(f'{first_name}:预约成功，流程结束', first_name, last_name)
                            return True
                        else:
                            retry_count += 1
                            logger.log_user(f'{first_name}:预约失败，重试次数: {retry_count}', first_name, last_name)
                    else:
                        logger.log_user(f'{first_name}:未找到合适的时间段', first_name, last_name)
                else:
                    logger.log_user(f'{first_name}:当前无可用时间段', first_name, last_name)
                
                # 等待后继续扫描
                time.sleep(self.config['scan_interval'])
                
            except Exception as e:
                logger.log_user(f'{first_name}:处理异常 - {e}', first_name, last_name)
                retry_count += 1
                time.sleep(5)  # 异常后等待5秒
        
        logger.log_user(f'{first_name}:达到最大重试次数，流程结束', first_name, last_name)
        return False
    
    def _is_working_hours(self) -> bool:
        """检查是否在工作时间内"""
        current_time = datetime.datetime.now().time()
        start_time = datetime.time(*map(int, self.config['working_hours']['start'].split(':')))
        end_time = datetime.time(*map(int, self.config['working_hours']['end'].split(':')))
        
        return start_time <= current_time <= end_time
    
    def _get_scan_dates(self) -> List[str]:
        """获取扫描日期范围 - 默认当月，无数据时往后延1个月"""
        from datetime import datetime, timedelta
        import calendar
        
        # 获取当前日期
        now = datetime.now()
        current_year = now.year
        current_month = now.month
        
        # 获取当月所有日期
        current_month_dates = []
        days_in_current_month = calendar.monthrange(current_year, current_month)[1]
        
        for day in range(1, days_in_current_month + 1):
            date = datetime(current_year, current_month, day)
            if date >= now:  # 只包含今天及以后的日期
                current_month_dates.append(date.strftime('%Y-%m-%d'))
        
        # 如果当月没有日期（月末情况），添加下个月
        if not current_month_dates:
            next_month = current_month + 1 if current_month < 12 else 1
            next_year = current_year if current_month < 12 else current_year + 1
            days_in_next_month = calendar.monthrange(next_year, next_month)[1]
            
            for day in range(1, min(days_in_next_month + 1, 32)):  # 最多31天
                date = datetime(next_year, next_month, day)
                current_month_dates.append(date.strftime('%Y-%m-%d'))
        
        # 如果当月日期少于7天，添加下个月的前几天
        if len(current_month_dates) < 7:
            next_month = current_month + 1 if current_month < 12 else 1
            next_year = current_year if current_month < 12 else current_year + 1
            days_in_next_month = calendar.monthrange(next_year, next_month)[1]
            
            # 添加下个月的前7天
            for day in range(1, min(8, days_in_next_month + 1)):
                date = datetime(next_year, next_month, day)
                current_month_dates.append(date.strftime('%Y-%m-%d'))
        
        logger.log(f'扫描日期范围: {current_month_dates[:5]}...{current_month_dates[-3:]} (共{len(current_month_dates)}天)', 'system')
        return current_month_dates
    
    def _is_task_paused(self, candidate_name: str) -> bool:
        """检查任务是否被暂停"""
        try:
            # 导入全局任务状态
            import sys
            import os
            sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
            from app import task_status
            
            # 检查全局暂停状态
            if task_status['paused']:
                return True
            
            # 检查特定任务暂停状态
            if self.user_id in task_status['paused_tasks']:
                return True
            
            return False
        except Exception as e:
            logger.log(f'检查任务暂停状态失败: {e}', 'system')
            return False
    
    def _is_time_in_range(self, time_str: str, date_range: List[str]) -> bool:
        """检查时间是否在指定日期范围内"""
        try:
            # 解析时间字符串，格式如 "2025-10-15T09:00:00"
            time_date = time_str.split('T')[0]  # 提取日期部分
            return time_date in date_range
        except Exception as e:
            logger.log(f'时间范围检查失败: {e}', 'system')
            return True  # 如果检查失败，默认允许预约
    
    def run_all_candidates(self) -> List[bool]:
        """运行所有候选人的预约流程"""
        results = []
        for candidate_name in CANDIDATES.keys():
            result = self.run_candidate(candidate_name)
            results.append(result)
        return results


# 全局主服务实例
main_service = MainService()
